import { AuthPayload, User } from '@/generated/graphql'
import { defineStore } from 'pinia'
import { useSession } from './useSession'

/**
 * 用户登录相关 hook
 */

interface AuthHook {
  _token: string | null
  _user?: User
}

export const useUserStore = defineStore({
  id: 'auth',
  persist: {
    storage: sessionStorage
  },
  state: (): AuthHook => ({
    _token: null,
    _user: undefined
  }),
  getters: {
    authenticated: (state) => !!state._token,
    token: (state) => state._token,
    user: (state) => state._user
  },
  actions: {
    M_setAuthState(authPayload: AuthPayload) {
      const _session = useSession()
      _session.setSession(authPayload.user?.session)

      this.$patch({
        _token: authPayload.token,
        _user: authPayload.user as User
      })
    },
    M_logout() {
      this.$reset()
    }
  }
})
